#include "YunDunPublicLib.h"

//Unicode (UTF-16) ת UTF-8
std::string Utf16ToUtf8(std::wstring utf16_string)
{
    if (utf16_string.empty()) return std::string();

    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &utf16_string[0], (int)utf16_string.size(), NULL, 0, NULL, NULL);
    std::string utf8_string(size_needed, 0);
    WideCharToMultiByte(CP_UTF8, 0, &utf16_string[0], (int)utf16_string.size(), &utf8_string[0], size_needed, NULL, NULL);

    return utf8_string;
}

//UTF-8 ת Unicode (UTF-16)
std::wstring Utf8ToUtf16(std::string utf8_string)
{
    if (utf8_string.empty()) return std::wstring();

    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &utf8_string[0], (int)utf8_string.size(), NULL, 0);
    std::wstring utf16_string(size_needed, 0);
    MultiByteToWideChar(CP_UTF8, 0, &utf8_string[0], (int)utf8_string.size(), &utf16_string[0], size_needed);

    return utf16_string;
}

//Unicode (UTF-16) ת ASCII
std::string Utf16ToAscii(std::wstring utf16_string)
{
    if (utf16_string.empty()) return std::string();

    int size_needed = WideCharToMultiByte(CP_ACP, 0, &utf16_string[0], (int)utf16_string.size(), NULL, 0, NULL, NULL);
    std::string ascii_string(size_needed, 0);
    WideCharToMultiByte(CP_ACP, 0, &utf16_string[0], (int)utf16_string.size(), &ascii_string[0], size_needed, NULL, NULL);

    return ascii_string;
}

//ASCII ת Unicode (UTF-16)
std::wstring AsciiToUtf16(std::string ascii_string)
{
    if (ascii_string.empty()) return std::wstring();

    int size_needed = MultiByteToWideChar(CP_ACP, 0, &ascii_string[0], (int)ascii_string.size(), NULL, 0);
    std::wstring utf16_string(size_needed, 0);
    MultiByteToWideChar(CP_ACP, 0, &ascii_string[0], (int)ascii_string.size(), &utf16_string[0], size_needed);

    return utf16_string;
}